package com.kxxnzstdsw.plugins

import com.kxxnzstdsw.exception.CanThrowException
import com.kxxnzstdsw.exception.ExceptionCode
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.response.*
import kotlinx.serialization.Serializable

fun Application.configureHTTP() {
//  跨域配置 按需配置
  install(CORS) {
    allowMethod(HttpMethod.Options)
    allowMethod(HttpMethod.Put)
    allowMethod(HttpMethod.Delete)
    allowMethod(HttpMethod.Patch)
    allowHeader(HttpHeaders.Authorization)
    allowHeader("MyCustomHeader")
    anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
  }
  install(DefaultHeaders) {
    header("X-Engine", "Ktor") // will send this header with each response
  }
}


@Serializable
data class SuccessData<T>(
  val success: Boolean = true,
  val data: T?
)

@Serializable
data class ErrorData<T>(
  val success: Boolean = false,
  val code: ExceptionCode,
  val errors: T?
)

suspend inline fun ApplicationCall.success() {
  respond(
    HttpStatusCode.OK,
    SuccessData(true, null)
  )
}

suspend fun ApplicationCall.success(data: String) {
  respondText(
    """
      {
        "success": true,
        "data": "$data"
      }
    """.trim(),
    ContentType.Application.Json
  )
}

suspend inline fun <T> ApplicationCall.success(data: T?) {
  respond(
    HttpStatusCode.OK,
    SuccessData(true, data),
  )
}

suspend fun ApplicationCall.error(error: CanThrowException, status: HttpStatusCode = HttpStatusCode.BadRequest) {
  respond(
    status,
    ErrorData(
      success = false,
      code = error.code,
      error.message
    )
  )
}

suspend inline fun ApplicationCall.error(
  message: String,
  code: ExceptionCode,
  status: HttpStatusCode = HttpStatusCode.BadRequest
) {
  respond(
    status,
    ErrorData(
      success = false,
      code = code,
      message
    )
  )
}
